import {
    // login,
    logout,
    // getUserInfo,
    getMessage,
    getContentByMsgId,
    hasRead,
    removeReaded,
    restoreTrash,
    getUnreadCount,
    getRouter
} from '@/api/user'
import { getRouter as getRouterr } from '@/api/data.js'
import {
    getBreadCrumbList,
    setTagNavListInLocalstorage,
    getMenuByRouter,
    getTagNavListFromLocalstorage,
    getHomeRoute,
    getNextRoute,
    routeHasExist,
    routeEqual,
    getRouteTitleHandled,
    localSave,
    localRead
  } from '@/libs/util'
import { USER_MAP } from '@/mock/login.js'
import APIS from '@/api'

import { setToken, getToken } from '@/libs/util'
import service from '@/libs/service'
export default {
    state: {
        userName: '',
        userId: '',
        avatarImgPath: '',
        token: getToken(),
        access: '',
        // localStorage.getItem('RouterList') ||
        hasGetInfo: false,
        unreadCount: 0,
        messageUnreadList: [],
        messageReadedList: [],
        messageTrashList: [],
        messageContentStore: {},
        routerList: [],
        user: JSON.parse(localStorage.getItem('user') || '[]'),
        data: '',
        TOKEN: '',
        jj: [],
        points: ['CHAKAN', 'BIANJI', 'SHANCHU'],
        flag: ''
    },
    mutations: {
        headersToken(state, token) {
            state.flag = token
        },
        removeToken(state) {
            state.flag = ''
        },
        setData(state, data) {
            state.routerList = data
        },
        setToken(state, token) {
            state.TOKEN = token
        },
        // 获取路由权限信息
        setUser (state, user) {
            state.user = user  // 首次登录将用户信息赋值给user ,并且存入sessionStorage
            localStorage.setItem('user', JSON.stringify(user))
        },
        setRouter(state, res) {
            state.routerList = res
        },
        setAvatar (state, avatarPath) {
            state.avatarImgPath = avatarPath
        },
        setUserId (state, id) {
            state.userId = id
        },
        setUserName (state, name) {
            state.userName = name
        },
        setAccess (state, access) {
            state.access = access
        },
        setToken (state, token) {
            state.token = token
            setToken(token)
        },
        setHasGetInfo (state, status) {
            state.hasGetInfo = status
        },
        setMessageCount (state, count) {
            state.unreadCount = count
        },
        setMessageUnreadList (state, list) {
            state.messageUnreadList = list
        },
        setMessageReadedList (state, list) {
            state.messageReadedList = list
        },
        setMessageTrashList (state, list) {
            state.messageTrashList = list
        },
        updateMessageContentStore (state, { msg_id, content }) {
            state.messageContentStore[msg_id] = content
        },
        moveMsg (state, { from, to, msg_id }) {
            const index = state[from].findIndex(_ => _.msg_id === msg_id)
            const msgItem = state[from].splice(index, 1)[0]
            msgItem.loading = false
            state[to].unshift(msgItem)
        },
        SETROUTES(state, d) {
            router.matcher = new VueRouter({
              routes: resultAllroute,
            }).matcher
            state.ifChange = true
        }
    },
    getters: {
        async getROUTER() {
            const token = localStorage.getItem('token')
            console.log('获取的token', token);
            const res = await getRouterr({
                token
            })
            console.log('iiii', res);
            service.routerRes(res)
            this.$store.commit('setRouter', res)
        },
        menuLists: (state, getters, rootState) => {
            return getMenuByRouter(state.routerList, rootState.user.access)
        },
        messageUnreadCount: state => state.messageUnreadList.length,
        messageReadedCount: state => state.messageReadedList.length,
        messageTrashCount: state => state.messageTrashList.length
    },
    actions: {
        getTbMenuQueryData({ commit, state }, hebing) {
            return new Promise((resolve, reject) => {
                let webMenu = JSON.parse(localStorage.getItem('routers'))
                if (webMenu) {
                  try {
                    if (!state.routerList.length && hebing) {
                      commit('SETROUTES', filterAsyncRouter(webMenu))
                    }
                  } catch (error) {
                    console.log(error)
                  }
                  resolve(webMenu)
                } else {
                }
              })
        },
        abc() {
            const res = getRouter({
                token
            })
        },
        // 登录
        handleLogin ({ commit }, { userPhone, userPassword, platformCode }) {
            userPhone = userPhone.trim()
            return new Promise((resolve, reject) => {
                let res = { "code": 20000, "message": "调用成功", "data": { "userName": "张三", "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyTmFtZSI6IumDneS4veiKsyIsImV4cCI6MTY2NzYxMzU1NiwidXNlcklkIjoiOCJ9.IdOQRsW8cVHYysQFzLnF9VUrj5gwO-lv4v92AXMT0n4", "deptName": "淅川县" } }
                const data = res.data
                // localStorage.myData = JSON.stringify(data)
                localStorage.myData = JSON.stringify({ userName: '张三', deptName: '淅川县', token: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyTmFtZSI6IuWRqOaYjOS4viIsImV4cCI6MTY4MTg4NTAzMSwidXNlcklkIjoiMTAifQ.XN01fJ7ox9-xNEFqVzHPXuHtlog-HDJM43PqQ3_aNcM' })
                // commit('setToken', data.token)
                commit('setToken', 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyTmFtZSI6IuWRqOaYjOS4viIsImV4cCI6MTY4MTg4NTAzMSwidXNlcklkIjoiMTAifQ.XN01fJ7ox9-xNEFqVzHPXuHtlog-HDJM43PqQ3_aNcM')
                resolve(res)
                /*APIS.login({
                  userPhone,
                  userPassword,
                  platformCode
                })
                  .then(res => {
                    const data = res.data
                    localStorage.myData = JSON.stringify(data)
                    commit('setToken', data.token)
                    resolve(res)
                  })
                  .catch(err => {
                    reject(err)
                  })*/
            })
        },
        // 授权登录
        wxAuthlogin ({ commit }, { preAuthCode, expiresIn, state }) {
            return new Promise((resolve, reject) => {
                APIS.wxlogin({
                    auth_code: preAuthCode,
                    expires_in: expiresIn,
                    state: state
                })
                    .then(res => {
                        const data = res.data
                        localStorage.myData = JSON.stringify(data)
                        commit('setToken', data.token)
                        // commit('setToken', 'super_admin')
                        resolve(res)
                    })
                    .catch(err => {
                        reject(err)
                    })
            })
        },
        // 扫码登录
        handlegoLogin ({ commit }, { authCode }) {
            return new Promise((resolve, reject) => {
                APIS.goLogin({
                    authCode
                })
                    .then(res => {
                        if (res.data) {
                            const data = res.data
                            localStorage.myData = JSON.stringify(data)
                            commit('setToken', data.token)
                        }
                        resolve(res)
                    })
                    .catch(err => {
                        reject(err)
                    })
            })
        },
        // 企业微信自动登录
        qywxzddl ({ commit }, { code }) {
            return new Promise((resolve, reject) => {
                APIS.qywxneibu({
                    code
                })
                    .then(res => {
                        const data = res.data
                        localStorage.myData = JSON.stringify(data)
                        commit('setToken', data.token)
                        // commit('setToken', 'super_admin')
                        resolve(res)
                    })
                    .catch(err => {
                        reject(err)
                    })
            })
        },
        // 退出登录
        handleLogOut ({ state, commit }) {
            return new Promise((resolve, reject) => {
                /*APIS.islogOut()
                  .then(() => {
                    commit('setToken', '')
                    commit('setAccess', [])
                    localStorage.clear()
                    resolve()
                  })
                  .catch(err => {
                    reject(err)
                  })*/
                // 如果你的退出登录无需请求接口，则可以直接使用下面三行代码而无需使用logout调用接口
                commit('setToken', '')
                commit('setAccess', [])
                resolve()
            })
        },
        // 获取用户相关信息
        getUserInfo ({ state, commit }, products) {
            return new Promise((resolve, reject) => {
                try {
                    // getUserInfo(state.token)
                    // .then(res => {
                    const data = {}
                    data.access = service.accessOpen(USER_MAP.super_admin.access)
                    commit('setAccess', data.access)
                    commit('setHasGetInfo', true)
                    resolve(data)
                    // })
                    // .catch(err => {
                    //   reject(err)
                    // })
                } catch (error) {
                    reject(error)
                }
            })
        },
        // 此方法用来获取未读消息条数，接口只返回数值，不返回消息列表
        getUnreadMessageCount ({ state, commit }) {
            // getUnreadCount().then(res => {
            //   const { data } = res
            //   commit('setMessageCount', data)
            // })
        },
        // 获取消息列表，其中包含未读、已读、回收站三个列表
        getMessageList ({ state, commit }) {
            return new Promise((resolve, reject) => {
                getMessage()
                    .then(res => {
                        const { unread, readed, trash } = res.data
                        commit(
                            'setMessageUnreadList',
                            unread.sort(
                                (a, b) => new Date(b.create_time) - new Date(a.create_time)
                            )
                        )
                        commit(
                            'setMessageReadedList',
                            readed
                                .map(_ => {
                                    _.loading = false
                                    return _
                                })
                                .sort(
                                    (a, b) => new Date(b.create_time) - new Date(a.create_time)
                                )
                        )
                        commit(
                            'setMessageTrashList',
                            trash
                                .map(_ => {
                                    _.loading = false
                                    return _
                                })
                                .sort(
                                    (a, b) => new Date(b.create_time) - new Date(a.create_time)
                                )
                        )
                        resolve()
                    })
                    .catch(error => {
                        reject(error)
                    })
            })
        },
        // 根据当前点击的消息的id获取内容
        getContentByMsgId ({ state, commit }, { msg_id }) {
            return new Promise((resolve, reject) => {
                let contentItem = state.messageContentStore[msg_id]
                if (contentItem) {
                    resolve(contentItem)
                } else {
                    getContentByMsgId(msg_id).then(res => {
                        const content = res.data
                        commit('updateMessageContentStore', { msg_id, content })
                        resolve(content)
                    })
                }
            })
        },
        // 把一个未读消息标记为已读
        hasRead ({ state, commit }, { msg_id }) {
            return new Promise((resolve, reject) => {
                hasRead(msg_id)
                    .then(() => {
                        commit('moveMsg', {
                            from: 'messageUnreadList',
                            to: 'messageReadedList',
                            msg_id
                        })
                        commit('setMessageCount', state.unreadCount - 1)
                        resolve()
                    })
                    .catch(error => {
                        reject(error)
                    })
            })
        },
        // 删除一个已读消息到回收站
        removeReaded ({ commit }, { msg_id }) {
            return new Promise((resolve, reject) => {
                removeReaded(msg_id)
                    .then(() => {
                        commit('moveMsg', {
                            from: 'messageReadedList',
                            to: 'messageTrashList',
                            msg_id
                        })
                        resolve()
                    })
                    .catch(error => {
                        reject(error)
                    })
            })
        },
        // 还原一个已删除消息到已读消息
        restoreTrash ({ commit }, { msg_id }) {
            return new Promise((resolve, reject) => {
                restoreTrash(msg_id)
                    .then(() => {
                        commit('moveMsg', {
                            from: 'messageTrashList',
                            to: 'messageReadedList',
                            msg_id
                        })
                        resolve()
                    })
                    .catch(error => {
                        reject(error)
                    })
            })
        }
    }
}
